package com.mmall.util;

import com.mmall.common.RedisPool;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

@Slf4j
public class RedisPoolUtil {

	public static Long expire(String key, int exTime) { // 设置有效期。
														// expire是设置key的有效期是多久，单位是秒

		Jedis jedis = null;
		Long result = null;

		try {
			jedis = RedisPool.getJedis();
			result = jedis.expire(key, exTime);// 是否过期，用1和0表示
		} catch (Exception e) {
			log.error("expire key:{}  error", key, e);
			RedisPool.returnBrokenResource(jedis);
			return result;
		}
		RedisPool.returnResource(jedis);
		return result;
	}

	public static String setEx(String key, String value, int exTime) {

		Jedis jedis = null;
		String result = null;

		try {
			jedis = RedisPool.getJedis();
			result = jedis.setex(key, exTime, value);// 设置有效期
		} catch (Exception e) {
			log.error("setex key:{} value:{} error", key, value, e);
			RedisPool.returnBrokenResource(jedis);
			return result;
		}
		RedisPool.returnResource(jedis);
		return result;
	}

	public static String set(String key, String value) {

		Jedis jedis = null;
		String result = null;

		try {
			jedis = RedisPool.getJedis();
			result = jedis.set(key, value);
		} catch (Exception e) {
			log.error("set key:{} value:{} error", key, value, e);
			RedisPool.returnBrokenResource(jedis);
			return result;
		}
		RedisPool.returnResource(jedis);
		return result;
	}

	public static String get(String key) {

		Jedis jedis = null;
		String result = null;

		try {
			jedis = RedisPool.getJedis();
			result = jedis.get(key);
		} catch (Exception e) {
			log.error("set key:{}  error", key, e);
			RedisPool.returnBrokenResource(jedis);
			return result;
		}
		RedisPool.returnResource(jedis);
		return result;
	}

	public static Long del(String key) {

		Jedis jedis = null;
		Long result = null;

		try {
			jedis = RedisPool.getJedis();
			result = jedis.del(key);
		} catch (Exception e) {
			log.error("del key:{}  error", key, e);
			RedisPool.returnBrokenResource(jedis);
			return result;
		}
		RedisPool.returnResource(jedis);
		return result;
	}

//	public static void main(String[] args) {
//		Jedis jedis = RedisPool.getJedis();
//		System.out.println(jedis);
//		RedisPoolUtil.set("bb", "22");
//		String value = RedisPoolUtil.get("bb");
//		System.out.println(value);
//		RedisPoolUtil.setEx("keyex", "valex", 9);
//		RedisPoolUtil.expire("bb", 90);
//		RedisPoolUtil.del("bb");
//		System.out.println("ok");
//	}
}
